/**
 * @author EasonChan
 *
 * Nov 20, 2010
 */
package com.musicgeek.biz.user;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.musicgeek.biz.util.UserSecurityUtil;
import com.musicgeek.dao.User;
import com.musicgeek.util.SecurityUtil;

public class UserFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		Cookie[] cookies = req.getCookies();
		String userName = getUserName(cookies);
		if (userName != null) {
			// req.setAttribute(User.USER, userName);
			req.getSession().setAttribute(User.USER, userName);
		}
		chain.doFilter(request, response);
	}

	private String getLoginToken(Cookie[] cookies) {
		String userName = null;
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals("login_token"))
				userName = cookie.getValue();
		}
		return userName;
	}

	private String parserUserNameFromLoginToken(String loginToken) {
		int spliterIndex = loginToken
				.indexOf(UserSecurityUtil.LOGIN_TOKEN_SPLITER);
		String encodedUserName = loginToken.substring(0, spliterIndex);
		return SecurityUtil.decodeBase64(encodedUserName);
	}

	private String getUserName(Cookie[] cookies) {
		if (cookies != null && getLoginToken(cookies) != null) {
			String loginToken = getLoginToken(cookies);
			if (loginToken != null)
				return parserUserNameFromLoginToken(loginToken);
		}
		return null;
	}

	@Override
	public void destroy() {
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
